package com.bluemsun.answerapp.controller;

import com.bluemsun.answerapp.dto.ExportExecution;
import com.bluemsun.answerapp.entity.UserBean;
import com.bluemsun.answerapp.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2019/1/22.
 */
@Controller
@RequestMapping("/export")
public class ExportController {
    Logger logger = LoggerFactory.getLogger(ExportController.class);
    @Autowired
    private UserService userService;


    /**
     * 导出学生名单
     *
     * @param request
     * @param response
     * @param
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/exportStu", method = RequestMethod.GET)
    private Map<String, Object> exportStu(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> modelMap = new HashMap<String, Object>();
        UserBean userBean=(UserBean)request.getSession().getAttribute("user");
        int courseId=userBean.getCourseId();
        ExportExecution ee=null;
        try {
            ee = userService.exportStu(courseId);
            response.setHeader("content-disposition", "attachment;filename="
                    + URLEncoder.encode("学生名单.xls", "UTF-8"));
            OutputStream outputStream = response.getOutputStream();
            ee.getHssfWorkbook().write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            modelMap.put("success", false);
            modelMap.put("errMsg", e.getMessage());
            return modelMap;
        }
        modelMap.put("success", true);
        return modelMap;

    }
}